<!--角色管理/设置-->
<template>
  <div class="roleSet">
    <el-container>
      <el-header class="header">
        <div>
          <div class="title">{{ editForm.roleName }}</div>
          <div
            class="companyType"
            v-if="editForm.positionList && editForm.positionList.length > 0"
          >
            <span v-for="(item, index) in editForm.positionList" :key="index">
              {{ editForm.positionList[index].orgName }}
            </span>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-tabs v-model="activeName" @tab-click="changeTabs">
          <el-tab-pane label="子系统权限" name="first" class="first">
            <div class="save">
              <el-button type="primary" @click="saveRoleManagement"
                >保存</el-button
              >
            </div>
            <el-checkbox-group v-model="checkList">
              <div v-for="(item, index) in checkData" :key="index">
                <div class="title">{{ item.appGroupName }}</div>
                <el-checkbox
                  v-for="(item2, index2) in checkData[index].appList"
                  :key="index2"
                  :label="`${item2.appName}`"
                ></el-checkbox>
              </div>
            </el-checkbox-group>
            <el-form
              :model="appRoleForm"
              ref="appRoleForm"
              label-width="120"
              class="demo-ruleForm"
            >
              <el-form-item label="备注信息：">
                <el-input
                  type="textarea"
                  v-model="appRoleForm.roleDesc"
                ></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="操作权限" name="second">
            <div class="save">
              <el-button type="primary" @click="saveRoleManagement"
                >保存</el-button
              >
            </div>
            <el-form
              :model="roleResourceForm"
              ref="roleResourceForm"
              label-width="120"
              class="demo-ruleForm"
            >
              <el-form-item label="子系统">
                <el-select
                  v-model="roleResourceForm.appId"
                  placeholder="请选择"
                  @change="changeSystem"
                >
                  <el-option
                    v-for="item in roleResourceAppArr"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-tree
                v-show="treeData.length"
                ref="menuTree"
                class="tree-box"
                :data="treeData"
                :props="{label: 'resourceName'}"
                node-key="id"
                check-strictly
                show-checkbox
                default-expand-all
                highlight-current
                @check-change="nodeChange"
                @check="nodeCheck"
                :render-content="renderContent"
                :expand-on-click-node="false"
                :key="nodeKey"
                v-loading="treeLoading"
              />
              <el-form-item label="备注信息：">
                <el-input
                  type="textarea"
                  v-model="roleResourceForm.remarkResource"
                ></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="数据权限" name="third" class="third">
            <div class="save">
              <el-button type="primary" @click="saveRoleManagement"
                >保存</el-button
              >
            </div>
            <ul>
              <li>
                <el-radio v-model="radio" label="6">
                  <span class="roleDataType">个人</span>
                  <span>只能操作自己的数据</span>
                </el-radio>
              </li>
              <li>
                <el-radio v-model="radio" label="5">
                  <span class="roleDataType">所属岗位</span>
                  <span>能操作自己所属同级岗位的数据</span>
                </el-radio>
              </li>
              <li>
                <el-radio v-model="radio" label="4">
                  <span class="roleDataType">所属岗位及下级岗位</span>
                  <span>能操作自己、下属岗位、和自己同级属位的数据</span>
                </el-radio>
              </li>
              <li>
                <el-radio v-model="radio" label="3">
                  <span class="roleDataType">所属部门</span>
                  <span>能操作自己、下属、和自己所属部门的数据</span>
                </el-radio>
              </li>
              <li>
                <el-radio v-model="radio" label="2">
                  <span class="roleDataType">所属部门及下属部门</span>
                  <span
                    >所属部门及下属部门
                    能操作自己、下属和自己所属部门及其子部门的数据</span
                  >
                </el-radio>
              </li>
              <li>
                <el-radio v-model="radio" label="1">
                  <span class="roleDataType">全公司</span>
                  <span>能操作全公司的数据</span>
                </el-radio>
              </li>
            </ul>
            <el-form
              :model="roleDataForm"
              ref="roleDataForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="备注信息：">
                <el-input
                  type="textarea"
                  v-model="roleDataForm.remarkData"
                ></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import ElEditable from '@components/el-editable/door/index.vue'
import searchForm from '@components/search/index.vue'
import {
  roleGetRoleAuthApp, // 查询角色子系统权限列表
  roleUpdateRoleAuthApp, // 跟新角色子系统权限列表
  roleGetRoleAuthData, // 查询角色数据权限
  roleUpdateRoleAuthData, // 保存角色数据权限
  getAppListByRoleId, // 操作权限/子系统
  roleGetRoleAuthResource, // 查询角色菜单权限列表
  updateRoleAuthResource, // 保存角色菜单权限
  roleGetById // 分页查询角色列表
} from '@const/api_staffCenter.js'
import {hasIn} from 'lodash'
export default {
  name: 'roleSet',
  components: {ElEditable, searchForm},
  data() {
    return {
      activeName: 'first',
      checkList: [],
      checkData: [],
      radio: '',
      roleDataForm: {
        remarkData: ''
      },
      appRoleForm: {
        roleDesc: ''
      },
      roleResourceForm: {
        appId: '',
        remarkResource: ''
      },
      roleResourceAppArr: [],
      treeLoading: false,
      treeData: [],
      editForm: {
        id: '',
        name: '',
        roleDesc: '',
        defaultConfig: '',
        companyType: ''
      },
      editFormRules: {
        name: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        defaultConfig: [{required: true, message: '请选择', trigger: 'blur'}],
        companyType: [
          {required: true, message: '请选择企业类型', trigger: 'change'}
        ]
      },
      setCheckedKeys: [],
      menuTreeLinear: [],
      nodeKey: 1
    }
  },
  mounted() {
    this.getRoleById()
    this.getRoleApp()
    this.getRoleData(false)
    this.getAppList()
    let obj = {
      type: 'btn',
      arr: []
    }
    this.$store.commit('changeLayoutHandle', obj)
  },
  methods: {
    // 查询角色
    getRoleById() {
      this.$axios({
        method: 'GET',
        url: `${roleGetById}?id=${this.$route.query.id}`
      })
        .then(res => {
          if (res.data.code === '0') {
            let data = hasIn(res, ['data', 'payload']) ? res.data.payload : []
            this.editForm = data
            this.appRoleForm.roleDesc = data.remarkApp
            this.roleResourceForm.remarkResource = data.remarkResource
          }
        })
        .finally(() => {})
    },
    changeTabs(val) {
      if (val.name === 'second') {
        this.getAppList()
      }
    },
    // 保存
    saveRoleManagement() {
      if (this.activeName === 'first') {
        this.updateRoleAuthApp()
      }
      if (this.activeName === 'second') {
        this.updateRoleResource()
      }
      if (this.activeName === 'third') {
        this.updateRoleData()
      }
    },
    updateRoleAuthApp() {
      let checkIdList = []
      this.checkData.forEach(item => {
        if (item.appList.length > 0) {
          item.appList.forEach(item2 => {
            if (this.checkList.includes(item2.appName)) {
              checkIdList.push(item2.id)
            }
          })
        }
      })
      let data = {
        roleId: this.$route.query.id,
        appIdList: checkIdList,
        remarkApp: this.appRoleForm.roleDesc
      }
      this.$axios({
        method: 'POST',
        url: roleUpdateRoleAuthApp,
        data: data
      })
        .then(res => {
          if (res.data.code === '0') {
            this.$message.success('保存成功')
          }
        })
        .finally(() => {})
    },
    // 子系统权限
    getRoleApp() {
      this.$axios({
        method: 'GET',
        url: `${roleGetRoleAuthApp}?roleId=${this.$route.query.id}`
      })
        .then(res => {
          let data = hasIn(res, ['data', 'payload']) ? res.data.payload : []
          this.checkData = hasIn(res, ['data', 'payload'])
            ? res.data.payload
            : []
          data.forEach(item => {
            if (item.appList.length > 0) {
              item.appList.forEach(item2 => {
                if (item2.selected) {
                  this.checkList.push(item2.appName)
                }
              })
            }
          })
        })
        .finally(() => {})
    },
    // 根据角色/操作权限/子系统列表
    getAppList() {
      this.$axios({
        method: 'GET',
        url: `${getAppListByRoleId}?roleId=${this.$route.query.id}`
      })
        .then(res => {
          this.roleResourceAppArr = []
          let data = hasIn(res, ['data', 'payload']) ? res.data.payload : []
          data.forEach(item => {
            let obj = {
              value: item.id,
              label: item.appName
            }
            this.roleResourceAppArr.push(obj)
          })
        })
        .finally(() => {})
    },
    nodeCheck(data, checked) {
      checked.checkedNodes.forEach(item => {
        if (item.id === data.id && item.children) {
          // 向下选中所有子级
          this.selectedChildren(item.children, true, false)
        }
      })
    },
    nodeChange(data, status) {
      if (status) {
        // 向上选中所有父级
        if (data.id) {
          this.selectedParent(this.menuTreeLinear, data, true, false)
        }
      } else {
        // 向下取消所有子级
        this.$refs.menuTree.setChecked(data, false, false)
        if (data.children) {
          this.selectedChildren(data.children, false, false)
        }
      }
    },
    selectedParent(menuTreeLinear, data, status, status2) {
      menuTreeLinear.forEach(item => {
        if (item.id === data.parentId && data.id !== '0') {
          this.$refs.menuTree.setChecked(item, status, status2)
          this.selectedParent(menuTreeLinear, item, status, status2)
        }
      })
    },
    selectedChildren(data, status, status2) {
      data.forEach(item => {
        if (item.resourceType === 2) {
          this.$refs.menuTree.setChecked(item, true, false)
        } else {
          this.$refs.menuTree.setChecked(item, status, status2)
        }
        if (item.children && item.children.length > 0) {
          this.selectedChildren(item.children, status, status2)
        }
      })
    },
    // 选中的菜单/禁用菜单
    selectedRoleResource(data) {
      data.forEach(item => {
        if (item.selected || item.resourceType === 2) {
          this.setCheckedKeys.push(item.id)
          this.$refs.menuTree.setCheckedKeys(this.setCheckedKeys)
          if (item.resourceType !== 2) {
            this.setCheckedKeys.push('0')
            this.$refs.menuTree.setCheckedKeys(this.setCheckedKeys)
          }
        }
        if (item.resourceType === 2) {
          item.disabled = true
        }
        this.menuTreeLinear.push(item)
        if (item.children && item.children.length > 0) {
          this.selectedRoleResource(item.children)
        }
      })
    },
    // 更新菜单权限
    updateRoleResource() {
      let resourceIdList = []
      this.$refs.menuTree.getCheckedNodes(false, true).forEach(item => {
        if (item.id) {
          resourceIdList.push(item.id)
        }
      })
      this.$axios({
        method: 'POST',
        url: updateRoleAuthResource,
        data: {
          roleId: this.$route.query.id,
          appId: this.roleResourceForm.appId,
          resourceIdList: resourceIdList,
          remarkResource: this.roleResourceForm.remarkResource
        }
      })
        .then(res => {
          if (res.data.code === '0') {
            this.$message.success('保存成功')
          }
        })
        .finally(() => {})
    },
    changeSystem(val) {
      this.getRoleResource()
    },
    // 菜单权限
    getRoleResource() {
      this.treeLoading = true
      if (!this.roleResourceForm.appId) {
        this.$message.error('请选择子系统')
      }
      this.$axios({
        method: 'GET',
        url: `${roleGetRoleAuthResource}?roleId=${this.$route.query.id}&appId=${this.roleResourceForm.appId}`
      })
        .then(res => {
          this.$refs.menuTree.setCheckedKeys([])
          let treeData = hasIn(res, ['data', 'payload']) ? res.data.payload : []
          this.pushTree(treeData)
          this.setCheckedKeys = []
          this.selectedRoleResource(this.treeData)
        })
        .finally(() => {
          this.treeLoading = false
        })
    },
    // 拼接数据结构
    pushTree(arr) {
      let label = ''
      this.roleResourceAppArr.forEach(item => {
        if (this.roleResourceForm.appId === item.value) {
          label = item.label
        }
      })
      this.treeData = [
        {resourceName: label, id: '0', selected: false, children: arr}
      ]
    },
    renderContent(h, {node, data}) {
      if ((data.children && data.children.length) || !data.id) {
        return (
          <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
            <span>
              <span style="margin-right:10px;">{node.label}</span>
              {node.data.resourceType == '1' ||
              node.data.resourceType == '3' ? (
                <el-tag size="mini">菜单</el-tag>
              ) : (
                <el-tag type="success" size="mini">
                  系统
                </el-tag>
              )}
            </span>
          </span>
        )
      } else {
        return (
          <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
            <span>
              <span style="margin-right:10px;">{node.label}</span>
              {node.data.resourceType == '1' ? (
                <el-tag size="mini">菜单</el-tag>
              ) : (
                ''
              )}
              {node.data.resourceType == '2' ? (
                <el-tag size="mini" type="warning">
                  按钮
                </el-tag>
              ) : (
                ''
              )}
              {node.data.resourceType == '3' ? (
                <el-tag size="mini">菜单</el-tag>
              ) : (
                ''
              )}
            </span>
          </span>
        )
      }
    },
    // 更新数据权限
    updateRoleData() {
      let data = {
        roleId: this.$route.query.id,
        remarkData: this.roleDataForm.remarkData,
        dataAuth: this.radio
      }
      this.$axios({
        method: 'POST',
        url: roleUpdateRoleAuthData,
        data: data
      })
        .then(res => {
          this.getRoleData()
          this.$message.success('操作成功')
        })
        .finally(() => {})
    },
    // 数据权限
    getRoleData() {
      this.$axios({
        method: 'GET',
        url: `${roleGetRoleAuthData}?roleId=${this.$route.query.id}`
      })
        .then(res => {
          let data = hasIn(res, ['data', 'payload']) ? res.data.payload : []
          this.radio = data.dataAuth ? data.dataAuth.toString() : ''
          this.roleDataForm.roleDesc = data.roleDesc
          this.roleDataForm.remarkData = data.remarkData
        })
        .finally(() => {})
    }
  }
}
</script>
<style lang="less">
.roleSet {
  display: flex;
  flex-direction: column;
  .header {
    display: flex;
    justify-content: space-between;
    .title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  .save {
    display: flex;
    justify-content: flex-end;
  }
  .first {
    .title {
      font-size: 16px;
      border-bottom: 1px solid #e4e7ed;
      margin-top: 30px;
    }
    .demo-ruleForm {
      margin-top: 30px;
    }
  }
  .third {
    li {
      list-style-type: none;
      .roleDataType {
        width: 150px;
        display: inline-block;
        padding: 10px 0;
      }
    }
  }
  .el-form {
    .el-input {
      width: 211px;
    }
  }
  .el-table {
    flex: 1;
  }
}
</style>
